<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="广告类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择广告类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:advertising:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:advertising:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:advertising:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:advertising:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="advertisingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" width="50px" />
      <!-- <el-table-column label="广告描述" align="center" prop="content" /> -->
      <el-table-column label="图片地址" align="center" prop="url" width="500px" />
      <!-- <el-table-column label="点击跳转" align="center" prop="clickTo" /> -->
      <el-table-column label="广告类型" align="center" prop="type">
			  <template slot-scope="scope">
			    <span v-if="scope.row.type == 0">首页轮播</span>
			    <span v-if="scope.row.type == 1">首页固定广告</span>
			  </template>
			</el-table-column>
			<el-table-column label="创建时间" align="center" prop="createTime" width="160">
			  <template slot-scope="scope">
			    <span>{{ parseTime(scope.row.createTime) }}</span>
			  </template>
			</el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:advertising:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:advertising:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告信息 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片地址" prop="content">
          <!-- <el-input v-model="form.url" type="textarea" placeholder="请输入图片地址" /> -->
          <el-upload
            action="https://jsonplaceholder.typicode.com/posts/"
            list-type="picture-card"
            :limit="1"
            :multiple="false"
            :file-list="mianFileLists"
            :on-change="mainImgBeforeupload"
            :auto-upload="false"
            :on-success="unloadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="广告类型" prop="type">
					<el-select v-model="form.type" placeholder="请选择类型" style="width: 100%;">
					  <el-option
					    v-for="dict in typeOptions"
					    :key="dict.dictValue"
					    :label="dict.dictLabel"
					    :value="dict.dictValue"
					  ></el-option>
					</el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAdvertising, getAdvertising, delAdvertising, addAdvertising, updateAdvertising, exportAdvertising,delImg } from "@/api/travel/advertising";

export default {
  name: "Advertising",
  data() {
    return {
      // 展示图url
      dialogImageUrl: '',
      // 展示图是否显示
      dialogVisible: false,
      //主图文件
      mainImgs: null,
      //修改时默认图片
      // fileLists: [{name: 'food.jpg', url: 'https://img.myliwoo.top/advertising/202006/0913423212540d7_original.jpg'},{name: 'food.jpg', url: 'https://img.myliwoo.top/advertising/202006/0913423212540d7_original.jpg'}],
      mianFileLists: [],//主图
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 广告信息 表格数据
      advertisingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 广告类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        content: undefined,
        url: undefined,
        clickTo: undefined,
        type: undefined,
        operatorId: undefined,
        createTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("tr_advertising_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 主图上传前
    mainImgBeforeupload (file) {
      this.mainImgs = file.raw;
      return false
    },
    //上传成功
    unloadSuccess(response, file, fileLis) {
      console.log(response);
    },
    //移除图片
    handleRemove(file, fileList) {
      if(file.status == "ready"){  //未上传的图
        this.mainImgs = null;
      }else if(file.status == "success"){//已上传的图
        let param = {
          id:this.form.id,
          delImg:file.name
        }
        this.mianFileLists = [];
        this.form.images = "";
        delImg(param).then(response => {
          this.msgSuccess("图片已删除");
        });
      }
    },
    /** 查询广告信息 列表 */
    getList() {
      this.loading = true;
      listAdvertising(this.queryParams).then(response => {
        this.advertisingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 广告类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        content: undefined,
        url: undefined,
        clickTo: undefined,
        type: undefined,
        operatorId: undefined,
        createTime: undefined
      };
      this.mianFileLists = [];//主图
      this.mainImgs = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告信息 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAdvertising(id).then(response => {
				response.data.type = response.data.type + "";
        this.form = response.data;
        this.mianFileLists = this.jointImageUrl(this.form.url);
        this.open = true;
        this.title = "修改广告信息 ";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        let formData = new FormData();
        formData.append("content",this.form.content);
        formData.append("url",this.form.url);
        formData.append("clickTo",this.form.clickTo);
        formData.append("type",this.form.type);
        if (valid) {
          if (this.form.id != undefined) {
            if(this.mainImgs == null && (this.form.url == "" || this.form.url == null)){
              this.msgError("需要上传主图");
              return;
            }
            if(this.mainImgs != null){
              formData.append("mainImgs",this.mainImgs);
            }
            formData.append("id",this.form.id);
            updateAdvertising(formData).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            if(this.mainImgs == null){
              this.msgError("需要上传主图");
              return;
            }
            formData.append("mainImgs",this.mainImgs);
            addAdvertising(formData).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除广告信息 编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAdvertising(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有广告信息 数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAdvertising(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style>
  .v-modal{
    z-index: 2000 !important;
  }
</style>
